# -*- coding: utf-8 -*-
import cgi, os,sys,math
import wsgiref.handlers
import  google.appengine.api

# Google App Engine imports.
from google.appengine.ext import webapp
from google.appengine.ext.webapp import util
from google.appengine.ext.webapp import template, \
	WSGIApplication
from google.appengine.api import users
##import app.webapp as webapp2
from google.appengine.ext import db

# Force Django to reload its settings.

from datetime import datetime ,timedelta
import base64,random
from django.utils import simplejson
import filter  as myfilter
from django.template.loader import *

from base import *
from model import *



class Search(BaseRequestHandler):
    def get(self): 
        return self.render('search_page',self.template_vals)

class Test(webapp.RequestHandler):
    def get(self):
        self.response.headers['Content-Type'] = 'text/plain'
        self.response.out.write('OK')
        

class mediaReUrl(webapp.RequestHandler):
    def get(self,key):
        self.redirect('http://tinyurl.chaoskey.com/'+key) 
        self.response.set_status(301)

htmlMap = {'2007/11/BLOG-POST_27':'2007/11/27/28',
           '2006/12/BLOG-POST_3622':'2006/12/19/16',
           '2006/12/BLOG-POST_6916':'2006/12/21/18',
           '2007/01/BLOG-POST':'2007/01/31/22',
           '2007/01/BLOG-POST_30':'2007/02/1/23',
           '2007/11/BLOG-POST':'2007/11/11/24',
           '2007/12/BLOG-POST':'2007/12/3/29',
           '2007/12/BLOG-POST_03':'2007/12/4/31',
           '2007/12/BLOG-POST_28':'2008/01/12/69',
           '2006/12/BLOG-POST_4417':'2007/12/5/32',
           '2007/12/BLOG-POST_6616':'2007/12/6/34',
           '2007/12/LOUNGE':'2007/12/6/35',
           '2007/12/BLOG-POST_4057':'2007/12/7/37'}    
class htmlReUrl(webapp.RequestHandler):
    def get(self,key):
        logging.info("301 redirect : " + key)
        new = htmlMap.get(key.upper())
        if new :
            self.redirect('/'+new)
        else :
            self.redirect('/') 
        self.response.set_status(301)

class RandomPostReUrl(webapp.RequestHandler): 
    def get(self): 
        r=random.randint(0,g_blog.entrycount)
        rs=Entry.all().fetch(1, r)
        if rs and len(rs)==1 :
            url='/'+rs[0].link
            self.redirect(url)              
        else:
            self.redirect(g_blog.baseurl)
        self.response.set_status(302)

postMap = {'2009/03/09/%E7%B3':'2009/03/9/200903092057'}    
class postReUrl(webapp.RequestHandler):
    def get(self,key):
        logging.info("301 redirect : " + key)
        new = postMap.get(key.upper())
        if new :
            self.redirect('/'+new)
        else :
            self.redirect('/') 
        self.response.set_status(301)

class backslashReUrl(webapp.RequestHandler):
    def get(self,key):
        logging.info("301 redirect : " + key)
        p=re.compile(r'/+')
        key=p.sub('/',key)                
        self.redirect('/'+key)
        self.response.set_status(301)

class linkReUrl(webapp.RequestHandler):
    def get(self,year,month,day,slug):
        logging.info("301 redirect : " + '/'+year + '/' + month + '/' +day+"/"+slug)               
        self.redirect('/'+year + '/' + month + '/' +day+"/"+slug)
        self.response.set_status(301) 

def main():
	urls=	[('/search', Search),
		 ('/test', Test),
                 ('/([\\w\\-]+)\\.mp3', mediaReUrl),
                 ('/(.*?)\\.html', htmlReUrl),
                 ('/sjwz', RandomPostReUrl),
                 ('/(2009/03/09/%[Ee]7%[Bb]3)[^/]*/', postReUrl),
                 ('/(.*?//.+?)', backslashReUrl),
                 ('/(.+?)/', backslashReUrl),
                 ('/(\d{4})/(\d{2})/0(\d)/(.+)',linkReUrl)]
	application = webapp.WSGIApplication(urls,debug=False)
	wsgiref.handlers.CGIHandler().run(application)

if __name__ == "__main__":
	main()
